package com.qf.demo3.Utils;

import com.qf.demo3.entity.Address;
import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WriteExcel {

    /**
     * 向Excel中写入数据
     * @param args
     * @throws Exception
     */
    public static void write(List<Address> list, String filePath) throws Exception {

//        List<Address> list = new ArrayList<Address>();
//        list.add(new Address(1,"北京市","北京市","丰台区","六里桥街道","六里桥1号"));
//        list.add(new Address(2,"北京市","北京市","丰台区","六里桥街道","六里桥2号"));
//        list.add(new Address(3,"北京市","北京市","丰台区","六里桥街道","六里桥3号"));


        boolean flag = fileExist(filePath);
        if (flag){
            writeExcel(list,filePath);
        }else {
            File file = new File(filePath);
            writeExcel(list,filePath);
        }
    }

    //判断文件是否存在
    public static boolean fileExist(String filePath){
        boolean flag = false;
        File file = new File(filePath);
        flag = file.exists();
        return flag;
    }

    //向Excel中写数据
    public static void writeExcel(List<Address> list ,String filePath){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("address");
        XSSFRow firstRow = sheet.createRow(0);//第一行表头
        XSSFCell cells[] = new XSSFCell[3];

        String[] titles = new String[]{"省、直辖市","市","区、县","街道","详细地址"};
        //循环设置表头信息
        for (int i=0;i<titles.length;i++){
            cells[0]=firstRow.createCell(i);
            cells[0].setCellValue(titles[i]);
        }

        //遍历list,将数据写入Excel中
        for (int i=0;i<list.size();i++){
            XSSFRow row = sheet.createRow(i+1);
            Address address = list.get(i);
            XSSFCell cell = row.createCell(0); //第一列
            cell.setCellValue(address.getProvince());
            cell=row.createCell(1); //第二列
            cell.setCellValue(address.getCity());
            cell=row.createCell(2); //第三列
            cell.setCellValue(address.getArea());
            cell=row.createCell(3); //第三列
            cell.setCellValue(address.getStreet());
            cell=row.createCell(4); //第三列
            cell.setCellValue(address.getAddress());

        }
        OutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            workbook.write(out);
            out.close();
        } catch (Exception e){
            e.printStackTrace();
        }

    }
}
